/*
 * frmSQLScriptReader.java
 *
 * Created on 1. März 2008, 09:06
 */

package com.googlecode.oskis.admin;
import java.sql.*;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JOptionPane;


/**
 * SQLScriptReader liest eine Textdatei mit SQL Statements, führt diese<br>
 * auf der Datenbank aus und zeigt das Ergebnis an.
 * @author  thomas
 */
public class frmSQLScriptReader extends javax.swing.JFrame {
    
    private File currentDir;
    private Connection db;
    
    
    /** Creates new form frmSQLScriptReader */
    public frmSQLScriptReader(Connection db) {
        initComponents();
        this.db=db;
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnOpenSQLScript = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtOutput = new javax.swing.JTextArea();
        btnClose = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("SQL Script Lesen");

        btnOpenSQLScript.setText("SQL Script lesen");
        btnOpenSQLScript.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpenSQLScriptActionPerformed(evt);
            }
        });

        txtOutput.setColumns(20);
        txtOutput.setRows(5);
        jScrollPane1.setViewportView(txtOutput);

        btnClose.setText("Schließen");
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                    .addComponent(btnOpenSQLScript)
                    .addComponent(btnClose))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnOpenSQLScript)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnClose)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /* Liest eine Textdatei mit SQL Anweisungen.
     * Die SQL Statements müssen am Anfang einer Zeile beginnen und enden mit einem
     * ';' als letztem Zeichen einer Zeile
     */
    private void btnOpenSQLScriptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpenSQLScriptActionPerformed
        String zeile;
        Statement st;
        StringBuffer SQL;
        BufferedReader reader;
        JFileChooser fc=new JFileChooser(currentDir);
        FileNameExtensionFilter fnf = new FileNameExtensionFilter("SQL Scripte","sql","txt");
        File selectedFile;
        fc.setFileFilter(fnf);
        int retVal=fc.showOpenDialog(this);
        if (retVal==JFileChooser.APPROVE_OPTION) {
            selectedFile=fc.getSelectedFile();
            currentDir=fc.getCurrentDirectory();
        } else {
            return;
        }
        try {
            reader=new BufferedReader(new FileReader(selectedFile));            
        } catch (FileNotFoundException fnfe) {
            JOptionPane.showMessageDialog(this,"Datei "+selectedFile+" nicht gefunden:\n"+fnfe);
            return;
        }
        SQL=new StringBuffer("");
        try {
            try {
                st=db.createStatement();
            } catch (SQLException sqle) {
                JOptionPane.showMessageDialog(this,"Datenbank Fehler:\n"+sqle);
                reader.close();
                return;
            }
            while ((zeile=reader.readLine())!=null) {
                SQL.append(zeile.replaceAll("\\s+"," ")).append(" ");
                if (zeile.indexOf(";")>0) {
                    try {
                        st.execute(SQL.toString());
                        txtOutput.append("OK\n");
                    } catch (SQLException sqle) {
                        txtOutput.append(SQL.toString().concat("\n"));
                        txtOutput.append(sqle.toString().concat("\n"));
                    }
                    SQL=new StringBuffer("");
                }
            }
            try {
                st.close();
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(this,e);
            }
            reader.close();
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(this, "IO Fehler:\n"+ioe);
        }
    }//GEN-LAST:event_btnOpenSQLScriptActionPerformed

    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_btnCloseActionPerformed
    

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClose;
    private javax.swing.JButton btnOpenSQLScript;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea txtOutput;
    // End of variables declaration//GEN-END:variables
    
}
